package com.yugao.fintech.antelope.base.model.module.mq;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSON;
import com.yugao.fintech.antelope.base.model.constants.ValidationCons;
import com.yugao.fintech.antelope.base.model.module.tenant.TenantContextHolder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import javax.validation.constraints.NotNull;
import java.util.Objects;


@Getter
@Setter
@ToString
public class BaseMqPayload {
    protected String msgId = RandomUtil.randomString(32);

    /**
     * 租户id
     */
    @NotNull(message = ValidationCons.NOT_EMPTY)
    protected Long tenantId;

    /**
     * 主租户
     */
    protected Long mainTenantId;

    public BaseMqPayload() {

    }

    /**
     * 初始化工作空间相关参数
     */
    public void initWorkspace() {
        if (Objects.isNull(this.tenantId)) {
            this.tenantId = TenantContextHolder.get().getTenantId();
        }
        if (Objects.isNull(this.mainTenantId)) {
            this.mainTenantId = TenantContextHolder.get().getMainTenantId();
        }
    }

    public String toMessage() {
        this.initWorkspace();
        return JSON.toJSONString(this);
    }


    public static <T extends BaseMqPayload> T parse(String msg, Class<T> tClass) {
        T t = JSON.parseObject(msg, tClass);
        TenantContextHolder.get().setTenantId(t.getTenantId());
        TenantContextHolder.get().setMainTenantId(t.getMainTenantId());
        return t;
    }
}
